<?php
/**
 *
 * @Allan
 * Date: 2020/12/4 12:31
 */

namespace app\common\traits;


use app\common\utils\Functions;
use app\common\model\Matchnotice as MatchNoticeModel;
use app\common\model\Sport\Score as SportScoreModel;
use app\common\model\Sport\Club as SportClubModel;
use app\common\model\Sport\Team as SportTeamModel;
use think\Exception;

trait MatchNotice
{

    /**
     * 查询 资源
     * @param array $param
     * @return SportScoreModel
     */
    private static function query($param = []){

        $query = MatchNoticeModel::where([]);

        if(isset($param['id']) && !empty($param['id'])){
            $query->where('id','=',intval($param['id']));
        }

        if(isset($param['type']) && !empty($param['type'])){
            $cList = SportClubModel::all(['type' => intval($param['type'])]);
            $query->where('country_id','in',array_column($cList,'country_id'));
        }

        if(isset($param['country_id']) && !empty($param['country_id'])){
            $query->where('country_id','in',explode(',',$param['country_id']));
        }

        if(isset($param['main_team_id']) && !empty($param['main_team_id'])){
            $query->where('main_team_id','in',explode(',',$param['main_team_id']));
        }

        if(isset($param['visiting_team_id']) && !empty($param['visiting_team_id'])){
            $query->where('visiting_team_id','in',explode(',',$param['visiting_team_id']));
        }

        if(isset($param['club_id']) && !empty($param['club_id'])){
            $query->where('club_id','in',explode(',',$param['club_id']));
        }

        if(isset($param['update_time_start']) && !empty($param['update_time_start'])){
            $query->where('update_time','>=',strtotime($param['update_time_start']));
        }
        if(isset($param['update_time_end']) && !empty($param['update_time_end'])){
            $query->where('update_time','<',strtotime($param['update_time_end']));
        }

        if(isset($param['match_time_start']) && !empty($param['match_time_start'])){
            $query->where('match_time','>=',strtotime($param['match_time_start']));
        }
        if(isset($param['match_time_end']) && !empty($param['match_time_end'])){
            $query->where('match_time','<',strtotime($param['match_time_end']));
        }

        if(isset($param['match_time']) && !empty($param['match_time'])){
            $match_time_arr = explode('~',trim($param['match_time']));
            $query->where('match_time','>=',strtotime(trim($match_time_arr[0])));
            $query->where('match_time','<',strtotime(trim($match_time_arr[1])));
        }

        return $query;

    }
    /**
     * 获取列表数据
     * @param array $param
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function getList($param = []){

        $is_get_all = $param['is_get_all'] ?? 0; //获取所有


        $order = ['match_time' , 'asc'];
        $order = isset($param['field']) && isset($param['order']) ? [trim($param['field']) , trim($param['order'])] : $order;


        $query = self::query($param);

        if(isset($param['team']) && !empty($param['team'])){
            $team = trim($param['team']);
            $query->where(function ($query) use ($team){
                $query->where('main_team','like','%'.$team.'%')
                    ->whereOr('visiting_team','like','%'.$team.'%');
            });
        }

        if(isset($param['team_id']) && !empty($param['team_id'])){
            $team_id = explode(',',trim($param['team_id']));
            $query->where(function ($query) use ($team_id){
                $query->where('main_team_id','in',$team_id)
                    ->whereOr('visiting_team_id','in',$team_id);
            });
        }


        $page = intval($param['page'] ?? 1);
        $per_page = intval($param['per_page'] ?? 1);
        $per_page = $per_page < 1 ? 10: $per_page;

        $total = $query->count();
        if($is_get_all) $per_page = $total;

        $query = self::query($param);
        $query = $query->order($order[0] ?? 'id' , $order[1] ?? 'desc' );
        $list = $query->page($page,$per_page)->select();

        $list = $list ? $list->toArray() : [];
        $list = self::formatList($list);

        $list_formate = $param['list_formate'] ?? 1;
        $list = self::formateJson($list,$list_formate);

        return Functions::formatList($list,$page,$per_page,$total,$list_formate == 1 ? true : false);
    }

    /**
     * 获取详情
     * @param $id
     * @param array $param
     * sn 单据号
     * @return bool
     */
    public function getDetail($id){
        $id = intval($id);
        if( $id <= 0 ) throw new Exception('参数错误',config('error_code.error'));
        $operator_id = intval(session('admin_id') ?? 0);
//        if( empty($operator_id) ) throw new Exception('操作人不能为空',config('error_code.error'));


        $obj = MatchNoticeModel::get($id);
        $data = $obj ? $obj->toArray() : null;
        return self::formatInfo($data,$operator_id);

    }

    /**
     * 添加对象
     * @param array $param
     */
    public static function mnAdd($param = []){

        $country_id =  intval($param['country_id']);
        $club_id =  intval($param['club_id']);
        $main_team =  trim($param['main_team']);
        $visiting_team =  trim($param['visiting_team']);
        $match_time =  trim($param['match_time']);
        $ori_match_time =  trim($param['ori_match_time']);

        if(empty($match_time)) throw new \Exception('比赛不能为空',config('error_code.error'));
        if(empty($country_id)) throw new \Exception('所属地区不能为空',config('error_code.error'));
        if(empty($club_id)) throw new \Exception('所属俱乐部不能为空',config('error_code.error'));
        if(empty($main_team)) throw new \Exception('主队不能为空',config('error_code.error'));
        if(empty($visiting_team)) throw new \Exception('客队不能为空',config('error_code.error'));

        $clubObj = SportClubModel::get($club_id);

        $match_time = strtotime($match_time);
        $isExist = MatchNoticeModel::getCount([
            ['match_time','=',$match_time],
            ['main_team','=',$main_team],
            ['visiting_team','=',$visiting_team],
        ]);

        if( $isExist>0 ) {
            $model = MatchNoticeModel::get([
                ['match_time','=',$match_time],
                ['main_team','=',$main_team],
                ['visiting_team','=',$visiting_team],
            ]);
        }else{
            $model = new MatchNoticeModel();
        }

        $countryArr = config('other.country') + config('other.country1');

        $model->ori_match_time = $ori_match_time;
        $model->match_time = $match_time;


        $model->main_team_id = intval($param['main_team_id']);
        $model->visiting_team_id = intval($param['visiting_team_id']);

        $model->main_team = $main_team;
        $model->visiting_team = $visiting_team;

        $model->club_id = $club_id;
        $model->club_name = $clubObj->name;

        $model->country_id = $country_id;
        $model->country_name = $countryArr[$country_id];

        $model->remark = $param['remark'] ?? '';

        $model->update_user = trim(session('admin_user') ?? '');//录单人
        $model->update_user_id = trim(session('admin_id') ?? 0);//录单人
        $model->update_time = time();

        $model->create_user = $model->update_user ;//录单人
        $model->create_user_id = $model->update_user_id;//录单人
//        $model->create_time = $model->update_time;

        $model->save();
        $id = $model->id;
        if( $id<=0 ) throw new \Exception('添加失败',config('error_code.error'));


        return [
            'id' => $id,
        ];

    }

    /**
     * 编辑对象
     * @param array $param
     * @param $id
     */
    public static function mnEdit($param = []){

        $id = intval($param['id']);
        $obj = MatchNoticeModel::getInfo(['id'=>$id]);
        if(empty($obj)) throw new \Exception('比分记录不存在',config('error_code.error'));

        if( isset($param['match_time']) ){
            $match_time =  trim($param['match_time']);
            if( empty($match_time) ) throw new \Exception('比赛时间不能为空',config('error_code.error'));
            $match_time = strtotime($match_time);
            $obj->match_time = $match_time;
        }

        if( isset($param['country_id']) ){
            $country_id =  intval($param['country_id']);
            $obj->country_id = $country_id;
            $clubObj = SportClubModel::getInfo([['id','=',$country_id,]]);
            $obj->country_name = config('other.country')[$country_id];        }

        if( isset($param['club_id']) ){
            $club_id =  intval($param['club_id']);
            $obj->club_id = $club_id;
            $clubObj = SportClubModel::getInfo([['id','=',$club_id,]]);
            $obj->club_name = $clubObj->name;
        }

        if( isset($param['main_team_id']) && !empty($param['main_team_id']) ) $obj->main_team = $param['main_team_id'];
        if( isset($param['main_team']) && !empty($param['main_team']) ) $obj->main_team = $param['main_team'];

        if( isset($param['visiting_team_id']) && !empty($param['visiting_team_id']) ) $obj->visiting_team_id = $param['visiting_team_id'];
        if( isset($param['visiting_team']) && !empty($param['visiting_team']) ) $obj->visiting_team = $param['visiting_team'];

        $obj->update_user = trim(session('admin_user') ?? '');//录单人
        $obj->update_user_id = trim(session('admin_id') ?? 0);//录单人
        $obj->update_time = time();

        $obj->save();



        return [
            'id' => $id,
        ];
    }

    /**
     * 删除记录
     * @param $id
     * @return bool
     */
    public static function delete($param){
        throw new \Exception('暂时不开放删除',config('error_code.error'));
        $id = $param['id'] ?? '';
        if ( empty($id) ) throw new \Exception('参数错误',config('error_code.error'));

        if( is_numeric($id) ){
            MatchNoticeModel::destroy(['id'=>$id]);
        }else{
            $ids = explode(',',trim($id));
            foreach ($ids as $id){
                MatchNoticeModel::destroy(['id'=>$id]);
            }
        }
        return  true;
    }

    /**
     * 格式化
     * @param $value
     * @return mixed
     */
    public static function format($value){
        if(isset($value['match_time'])) $value['match_time'] = Functions::formatDateTime($value['match_time'],'Y-m-d H:i');
        if(isset($value['create_time'])) $value['create_time'] = Functions::formatDateTime($value['create_time']);
        if(isset($value['update_time'])) $value['update_time'] = Functions::formatDateTime($value['update_time']);

        return $value;
    }

    /**
     * 格式化 info
     * @param $info
     */
    public static function formatInfo($info){
        if(!empty($info)){
            $info = self::format($info);
        }
        return $info;
    }

    /**
     * 格式化 list
     * @param $list
     * @param bool $isGetAssetsSn 是否获取 支出的资产编号 默认否
     * @return mixed
     */
    public static function formatList($list){

        if(!empty($list)){

            $clubList = SportClub::getList([
                'is_get_all' => 1,
                'order' => 'id asc',
            ])['data'];
            $clubList = Functions::getKeyValueList($clubList,'id');
            foreach ($list as $key => &$value){
                $value['club_name'] = $clubList[$value['club_id']]['name'] ?? '';
                $value = self::format($value);
            }
        }
        return $list;
    }

    protected static function formateJson($list,$formate_type = 1){
        if($formate_type == 1) return $list;
        if($formate_type == 2){//
            $data = [];
            foreach ($list as $key => $value){
                $value['team'] = $value['main_team'] .' ~ '. $value['visiting_team'];
                $date = Functions::formatDate(strtotime($value['match_time']));
                $data[$date][$value['country_id']][] = $value;
            }
            return $data;
        }

        return $list;
    }

    /**
     * 抓取数据
     * @param string $content
     */
    public static function graspMatchs($lines = ''){
        $total = $success = 0;
        if(!empty($lines)){

            $matchs = [];
            /// 独家FIFA 独家PES
            $team = $main_team = $visiting_team = '';

            $clubList = SportClubModel::all([]);
            $clubList = Functions::getKeyValueList($clubList,'id');

            $teamList = SportTeamModel::all([]);
            $teamList = Functions::getKeyValueList($teamList,'full_name');
            $lines = array_merge(array_filter($lines));

            $link = 0;//指针
            foreach ($lines as $key => $line){

                if( $key < $link ) continue;
                if(stripos($line,'独家FIFA') !== false || stripos($line,'独家PES') !== false ) continue;

                if(stripos($line,'VS - ') !== false ){
                    $main_team = trim($line);//主队
                    if(!isset($teamList[$main_team])) continue;
                    $visiting_team = trim($lines[$key + 1] ?? '');// 客队
                    if(!isset($teamList[$visiting_team])) continue;

                    $ori_match_time = trim($lines[$key-2]??'') . ' ' . trim($lines[$key-1]??'');
                    $match_time = self::formatMatchTime(trim($lines[$key-2]??''),trim($lines[$key-1]??''));

//                    Log::write('-------*********************-------' );
//                    Log::write($clubList[$club] );
//                    Log::write( $teamList[$main_team] );
//                    continue;

                    $club_id = $teamList[$main_team]['club_id'];

                    $match = [
                        'ori_match_time' => $ori_match_time,
                        'match_time' => $match_time,

                        'club_id' => $club_id,
                        'club_name' => trim($clubList[$club_id]['name']),
                        'country_id' => $clubList[$club_id]['country_id'],
                        'country_name' => $clubList[$club_id]['country_name'],

                        'main_team_id' => $teamList[$main_team]['id'],
                        'visiting_team_id' => $teamList[$visiting_team]['id'],

                        'main_team' => $main_team,
                        'visiting_team' => $visiting_team,

                        'remark' => '',

                    ];

                    $matchs[] = $match;

                    $link = $key + 2;// 跳过
                }
            }

            foreach ($matchs as $match){
                $total++;
                try{
                    self::mnAdd($match);
                    $success++;
                }catch (\Exception $e){
                    Log::write('----------- 添加失败数据start ----------');
                    Log::write($match);
                    Log::write($e->getMessage());
                }
            }
        }
        return [
            'total'=>$total,
            'success'=>$success,
        ];
    }

    private static function formatMatchTime($date,$time){
        $date = trim($date);
        $date = str_replace('\\','/',$date);
        $dateArr = explode('/',$date);
        $date = date('Y',time()). '-' .($dateArr[1] ?? '') . '-' . ($dateArr[0] ?? '');
        $time = strtolower(trim($time));
        if(stripos($time,'am') !== false){
            $time = str_replace('am','',$time);
            $addHour = 0;
        }else{
            $time = str_replace('pm','',$time);
            $addHour = 12;
        }
        $timeArr = explode(':',$time);
        if( $timeArr[0] == 12 ) $timeArr[0] = '00';

        $match_time_str = $date . ' ' . trim($timeArr[0]??'') . ':' . trim($timeArr[1]??'') .':00';
        return Functions::formatDateTime(strtotime($match_time_str) + (0 + $addHour) * 60 * 60);
    }

    /**
     * 下载比赛
     * @param array $param
     */
    public static function snycLoadMatch($param = []){

        $total = $success = 0;


        return [
            'total'=>$total,
            'success'=>$success,
        ];

    }


}